
rgbm=imread('lena.jpg');
gray=rgb2gray(rgbm);
[row,col]=size(gray);
imshow(gray)
title('原图')
numofgray=zeros(1,256);
for i=1:row
    for j=1:col
        numofgray(gray(i,j)+1)=numofgray(gray(i,j)+1)+1;%%统计每个灰度值的像素数
    end
end
gray_p=zeros(1,256);
total=row*col;
temp=0;
for i=1:256
    temp=temp+numofgray(i);
    gray_p(i)=temp/total;%统计相应的累计直方图
end
graylevel=linspace(0,255,256);
figure
plot(graylevel,gray_p)
title('原图的累计直方图')
r=(0:255);
sigma=30;
miu=120;
p=1/(sqrt(2*pi)*sigma)*exp(-((r-miu).^2)/(2*sigma^2));%单峰高斯函数的表达式
map_add_gray=zeros(1,256);
temp=0;
for i=1:256
    temp=temp+p(i);
    map_add_gray(i)=temp;%统计规定化之后的直方图
end
temp=0;
for i=1:256
    if(p(i)>=0.0001)
        temp=temp+1;%提取概率较大的灰度值，以0.0001为区分界限
    end
end
figure
plot(r,p)
title('高斯函数灰度级概率曲线')
reflect_p=zeros(1,temp);
reflect_gray=zeros(1,temp);
point=1;
for i=1:256
    if(p(i)>=0.0001)
        reflect_gray(point)=i-1;
        reflect_p(point)=map_add_gray(i);
        point=point+1;
    end
end          %找出灰度值的概率大于0.0001所对应灰度值的累计直方图，对映射之后的灰度值进行分组
[x,y]=size(reflect_p);
reflect_p(y)=1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%  SML
compare_result=zeros(1,temp);
final_gray=zeros(1,256);
point=1;
for i=1:256
    for j=1:temp
        compare_result(j)=abs(gray_p(i)-reflect_p(j));
    end
    [X,Y]=min(compare_result);
    final_gray(i)=reflect_gray(Y);
end    %确定映射关系
gray1=zeros(256,256);
for i=1:256
    for j=1:256
        gray1(i,j)=final_gray(gray(i,j)+1);
    end
end       %对原图灰度值进行变换，进行映射
gray1=uint8(gray1);
figure
imshow(gray1)
title('SML映射后直方图')
%%%%%%%%%%%%%%%%%%%%%%%      GML
compare_result2=zeros(1,256);
final_gray2=zeros(1,256);
temp1=1;
temp3=1;
temp2=1;
for i=1:temp
    for j=1:256
        compare_result2(j)=abs(reflect_p(i)-gray_p(j));
        [X,Y]=min(compare_result2);
    end
    if i==temp
        Y=256;
    end
    if temp2==Y
        temp1=temp3;
    end
    for j=temp1:Y
        final_gray2(j)=reflect_gray(i);
    end
    temp3=temp1;
    temp2=Y;
    temp1=Y+1;
end             %%确定映射关系
gray2=zeros(256,256);
for i=1:256
    for j=1:256
        gray2(i,j)=final_gray2(gray(i,j)+1);
    end
end             %对原图灰度值进行变换，进行映射
gray2=uint8(gray2);
figure
imshow(gray2)
title('GML映射后的图像')
numofgray=zeros(1,256);
for i=1:256
    for j=1:256
        numofgray(gray1(i,j)+1)=numofgray(gray1(i,j)+1)+1;
    end
end
graylevel=linspace(0,255,256);
figure
bar(graylevel,numofgray)%画SML映射之后得直方图
title('SML直方图')
numofgray=zeros(1,256);
for i=1:256
    for j=1:256
        numofgray(gray2(i,j)+1)=numofgray(gray2(i,j)+1)+1;
    end
end
graylevel=linspace(0,255,256);
figure
bar(graylevel,numofgray)%画GML映射之后得直方图
title('GML直方图')